package me.kuye.jkuye.helper;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import me.kuye.jkuye.plugin.activerecord.Config;
import me.kuye.jkuye.plugin.activerecord.Model;

public class DatabaseHelper {
	public static Config config;

	public static Config brokenConfig = new Config();

	private static Map<Class<? extends Model>, Config> modelToConfig = new HashMap<Class<? extends Model>, Config>();

	private static Map<String, Config> configNameToConfig = new HashMap<String, Config>();

	static final Object[] NULL_PARA_ARRAY = new Object[0];
	public static final String MAIN_CONFIG_NAME = "main";

	public static Config getConfig(String configName) {
		return config;
	}

	public static Config getConfig(Class<? extends Model> modelClass) {
		return modelToConfig.get(modelClass);
	}

	public static void addConfig(Config config) {
		if (config == null) {
			throw new IllegalArgumentException(" the config can not  be  null");
		}
		if (configNameToConfig.containsKey(config.getName())) {
			throw new IllegalArgumentException(" the config has exist");
		}

		configNameToConfig.put(config.getName(), config);

		if (MAIN_CONFIG_NAME.equals(config.getName())) {
			DatabaseHelper.config = config;
		}
		if (DatabaseHelper.config == null) {
			DatabaseHelper.config = config;
		}
	}

	static void putModelToConfig(Class<? extends Model> modelClass, Config config) {
		modelToConfig.put(modelClass, config);
	}

	public static void removeConfig(String configName) {
		if (DatabaseHelper.config != null && DatabaseHelper.config.getName().equals(configName)) {
			throw new RuntimeException(" can not remove the current config");
		}
		configNameToConfig.remove(configName);
	}

	public static final void closeQuietly(ResultSet rs, Statement st) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
			}
		}
		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
			}
		}
	}

	public static final void closeQuietly(Statement st) {
		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
			}
		}
	}

	public static String replaceFormatSqlOrderBy(String sql) {
		sql = sql.replaceAll("(\\s)+", " ");
		int index = sql.toLowerCase().lastIndexOf("order by");
		if (index > sql.toLowerCase().lastIndexOf(")")) {
			String sql1 = sql.substring(0, index);
			String sql2 = sql.substring(index);
			sql2 = sql2.replaceAll(
					"[oO][rR][dD][eE][rR] [bB][yY] [\u4e00-\u9fa5a-zA-Z0-9_.]+((\\s)+(([dD][eE][sS][cC])|([aA][sS][cC])))?(( )*,( )*[\u4e00-\u9fa5a-zA-Z0-9_.]+(( )+(([dD][eE][sS][cC])|([aA][sS][cC])))?)*",
					"");
			return sql1 + sql2;
		}
		return sql;
	}


}
